<?php
//nada
$this->pageTitle = "My Basket";
App::import('Vendor', 'prodmath');
$isAdmin = ($current_user['auth_type'] == AUTH_ADMIN);
$cashierCanEdit = ($isAdmin || $current_user['auth_type'] == AUTH_CASH);

$df = '%A, %B %e';

if ($cashierCanEdit) { 
	e($this->renderElement('memberVcard',array('m' => $member['Member'])));
	echo '<form action="', $html->url(array('controller'=>'members', 'action' => 'basket', $member['Member']['member_id'])), '" method="POST">';
}
?>
<h2>Your Basket <?php
	echo $html->link('[Printable PDF]', "/members/basket/" . $member['Member']['member_id'] . '.pdf', array('class'=>'action'));
	if ($cashierCanEdit) {
		e(' <a href="#add" class="action">[Add an Item]</a>');
	}
	?></h2>
<?php

$d = Configure::read('Delivery');
$isOpen = $d['is_open'];

echo '<h3>You are responsible for picking up these items on ' . strftime($df,strtotime($d["delivery_open"])) . '.</h3>';
echo '<p>If you cannot pick up these items at that time, find out how to <a href="/pages/arrangements">make other arragements.</a></p>';

?>
<p><em>Items in italics were marked as missing.</em></p>
<table>
<tr>
<th>Qty</th>
<th>Producer</th>
<th>Item</th>
<th>Unit Price</th>
<th>Weight (est)</th>
<th>Tax</th>
<th>Total</th>
<?php if ($cashierCanEdit) { e('<th>Actions</th>'); } ?>
</tr>
<?php
$total = 0;
$sTotal = 0;
$taxTotal = 0;
$cur = $current_delivery;
$sel = array('members-' . $member['Member']['member_id'] => 'This Order');
foreach($items as $item) {
  if ($item['orderables']['delivery_id'] == $cur) {
  
  	if ($cashierCanEdit) {
  		$q = $form->input('BasketItem.quantity_' . $item['basket_items']['id'], array('label'=>false, 'value'=>$item['basket_items']['quantity'], 'class'=>'quantity'))  . ' ' . $item['orderables']['ordered_by'];
    	$w = ($item['product_list']['random_weight'] == 0) ? 'N/A' : $form->input('BasketItem.weight_' . $item['basket_items']['id'], array('label'=>false, 'value'=>number_format($item['basket_items']['weight'],2), 'class'=>'quantity'))  . ' ' . $item['orderables']['priced_by'] . '(s)';
  	} else {
  		$q = $item['basket_items']['quantity']  . ' ' . $item['orderables']['ordered_by'];
    	$w = ($item['product_list']['random_weight'] == 0) ? 'N/A' : number_format($item['basket_items']['weight'],2) . ' ' . $item['orderables']['priced_by'] . '(s)';
  	}
  	
  	$sel['basket_items-' . $item['basket_items']['id']] = $item['product_list']['product_name'];
  	if ($item['basket_items']['missing']) { $q = '<em>' . $q . '</em>'; }
  	$item[0]['tax'] = ($item['product_list']['tax_exempt']) ? 0 : $item['product_list']['tax_exempt'] * SALES_TAX;
    echo '<tr><td>' . $q;
    if ($isOpen) { 
    	echo ' ' . $html->link('[Change]','/basketItems/edit/' . $item['basket_items']['id']); 
    	e(" " . $html->link('[Remove]','/basketItems/del/' . $item['basket_items']['id']));
    }
    echo "</td>\n";
    $m = ($item['basket_items']['missing']) ? '<em>' . $item['product_list']['product_name'] . '</em>': $item['product_list']['product_name'];
    echo '<td>' . $item['producer']['business_name'] . "</td>\n";
    echo '<td>' . $m . "</td>\n";
    echo '<td>$' . number_format($item['orderables']['price'],2) . ' per ' . $item['orderables']['priced_by'] . "</td>\n";
    echo '<td>' . $w . "</td>\n";
    if ($item['basket_items']['missing']) {
    	echo '<td>$' . number_format(0,2) . "</td>\n";
    	echo '<td>$' . number_format(0,2) . "</td>\n";
    } else {
    	echo '<td>$' . number_format(calcTax($item),2) . "</td>\n";
    	echo '<td>$' . number_format(calcTotal($item) + calcTax($item),2) . "</td>\n";
    }
    if ($cashierCanEdit) {
			$mmiss = ($item['basket_items']['missing']) ? $html->link('[mark as delivered]', '/basketItems/markDelivered/' . $item['basket_items']['id']) : $html->link('[mark as missing]', '/basketItems/markMissing/' . $item['basket_items']['id']);
    	echo '<td>', join("<br/>", array(
    		$html->link('[Remove]','/basketItems/del/' . $item['basket_items']['id']),
    		$mmiss
    		)), "</td>\n";
    }
    echo "</tr>\n\n";
    //$total += $item['BasketItem']['total'] + $item['BasketItem']['tax'];
		$sTotal += ($item['basket_items']['missing']) ? 0 : round(calcTotal($item) * 100);
		$taxTotal += ($item['basket_items']['missing']) ? 0 : round(calcTax($item) * 100);
	}
}
?>
</table>

<?php

if ($cashierCanEdit) {
	e('<input type="submit" value="Save Basket"/></form>');
}
$adjTotal = 0;
foreach($notes as $note) {
	$tstring = ($note['Note']['adj_tax']) ? ' + Tax' : '';
	echo '<p><strong>Note from ', $note['From']['username'], ':</strong> ', $note['Note']['text'], ' Adjustment: $', number_format($note['Note']['adj_amount'], 2), $tstring, '</p>';
	if ($note['Note']['adj_tax']) {
		$taxTotal += round($note['Note']['adj_amount'] * SALES_TAX * 100);
	}
	if ($cashierCanEdit) {
		e($html->link('[Remove Note]', '/members/removeNote/'.$note['Note']['id']));
	}
	$adjTotal += $note['Note']['adj_amount'] * 100;
}

//$total = round(($total) * 100)/100;
$surcharge = round((MEMB_SURCHARGE/100) * $sTotal);
$total = (($sTotal + $adjTotal + $taxTotal + $surcharge)/100);
$df = '%B %e, %Y';


$mtime = strtotime($member['Member']['paid_fee'] . ' +' . Configure::read('Membership.valid_for'));
$ptime = strtotime(date('r', $mtime) . ' -' . Configure::read('Membership.ask_for_fee'));
$now = time();
$due = strftime($df,$mtime);
$member_message = '';
if ($now > $mtime) {
  $member_message = 'Your membership fee of $' . $member['Member']['memb_amt_owed'] . ' is due as of ' . $due . '.  Your total is adjusted below.';
} else if ($now > $ptime) {
  $member_message = 'Your membership fee of $' . $member['Member']['memb_amt_owed'] . ' will be due '. $due . '.  Your total is adjusted below, but we can waive it for this invoice if you prefer.';
}else {
  $member_message = 'Your membership is paid through ' . $due . '.';
}
$m_fee = (time() > $ptime) ? $member['Member']['memb_amt_owed'] : 0;
?>
<p><?=$member_message?></p>
<p>Sub-Total: $<?=number_format($sTotal/100,2)?></p>
<p>Coop Surcharge (<?=MEMB_SURCHARGE?>%): $<?=number_format($surcharge/100,2)?></p>
<p>Membership Fee: - $<?=number_format($m_fee,2)?></p>
<p>Adjustments Total: $<?=number_format($adjTotal/100,2)?></p>
<p>Sales Tax: $<?=number_format($taxTotal/100,2)?></p>
<p>Total: $<?=number_format($total + $m_fee,2)?></p>
<?php

if ($cashierCanEdit) {
	$nl = "\n";
?>
<a name="add"></a>
<?php
if ($isAdmin) {
?>
	<p class="help"><strong>ADMINS:</strong> Please don't use the "Add Item" form below to shop.  It is only for invoice corrections - and it bypasses the Inventory system, so the producer's inventory quantities will be ignored and inaccurate if you use this form to shop during the cycle!</p>
<?php
}
?>
<p class="help"><strong>Adjustors:</strong> If you have multiple items with different weights, make sure to add them one at a time, please.  Don't forget to double-check your quantities and weights!</p>
<form id="AddItem" action="<?=$html->url('/basketItems/add')?>" method="post">
<fieldset>
	<legend>Add Item</legend>
	<div class="input select">
		<label for="ProducerId">Producer</label>
		<select name="data[Producer][producer_id]" id="ProducerId">
<?php
	foreach($producers as $producer) {
		if (!empty($producer['Member']['business_name'])) {
			echo '<option value="' . $producer['Producer']['producer_id'] . '">' . $producer['Member']['business_name'] . '</option>';
		}
	}
?>
		</select>
	</div>
	<div class="input select">
		<label for="ProductId">Product</label>
		<select name="data[Product][product_id]" id="ProductId">
		
		</select>
	</div>
	<?=$form->input('BasketItem.quantity', array('value'=>1, 'class'=>'quantity'))?>
	<?=$form->input('BasketItem.weight', array('label' => array('id'=>'BasketItemWeightLabel', 'text'=>'Price'), 'value'=>0, 'class'=>'quantity', 'after'=>'<span id="BasketItemWeightUnit"></span>'))?>
<input type="submit" value="Add Item"/>
</fieldset>
</form>
<p class="help"><strong>Adjustors:</strong> Notes should no longer be used to add items.  They are reserved for refunds and error correction.  If you can't find a product in the Add Item form above, select the producer, and use the "Other... (Misc Add-On)" product.  Don't forget to set the correct price.</p>
<?php
	
	echo '<form id="addNote" action="', $html->url('/members/basket/' . $member['Member']['member_id']),'" method="POST">', $nl;
	echo '<fieldset>', $nl;
	echo '<legend>Add Note to Invoice</legend>', $nl;
	//echo $html->hidden('Note/table_name', array('value'=>'members')), $nl;
	//echo $html->hidden('Note/table_id', array('value'=>$member['Member']['member_id'])), $nl;
	
	echo $form->hidden('Note.from_id', array('value'=>$current_user['member_id'])), $nl;
	echo $form->hidden('Note.delivery_id', array('value'=>$current_delivery)), $nl;
	
	echo $form->input('Note.table',array('label' => 'Regarding', 'options' => $sel, 'value'=>'members-' . $member['Member']['member_id'])), $nl;
	echo $form->input('Note.text', array('label' => 'Note', 'rows'=>'5', 'cols' => '50')), $nl;
	echo $form->input('Note.adj_amount', array('label' => 'Adjustment', 'value' => '0.00', 'class' => 'quantity')), $nl;
	echo $form->input('Note.adj_tax', array('type' => 'checkbox', 'label' => 'Apply Tax')), $nl;
	echo $form->submit('Add Note'), $nl;
	echo '</fieldset>', $nl;

	echo '</form>', $nl;
?>
<script type="text/javascript">
	var products = $A();
	
	function updateProductDropdown() {
		var dropdown = $('ProductId');
		var producer_id = $F('ProducerId');
		new Ajax.Request('<?=$html->url('/products/search')?>/producer_id:' + producer_id + '.json', { method: 'get', onSuccess: function(transport) {
			products = $A(eval(transport.responseText));
			var options = '<option value="0">Other... (Misc. Add-On)</option>';
			products.each(function(product){
				if (product.Product.product_name && !(Number(product.Product.donotlist))) {
					options = options + "\n" + '<option value="' + product.Product.product_id + '">' + product.Product.product_name + ' ($' + Number(product.Orderable.price).toFixed(2) + ' / ' + product.Orderable.priced_by + ')</option>';
				}
			});
			dropdown.update(options);
		}});
	}
	
	function updatePriceWeightLabel() {
		var product_id = $F('ProductId');
		var labelText = 'Price (ea.)';
		var unitText = ' Dollars';
		var value = 1;
		if (product_id != 0) {
			var selectedProduct = products.find(function(product){ return (product.Product.product_id == product_id); });
			if (selectedProduct.Product.random_weight != 0) {
				labelText = 'Weight';
				unitText = ' ' + selectedProduct.Orderable.priced_by + '(s) at $' + Number(selectedProduct.Orderable.price).toFixed(2) + ' per ' + selectedProduct.Orderable.priced_by;
				value = Number((Number(selectedProduct.Product.minimum_weight) + Number(selectedProduct.Product.maximum_weight)) / 2).toFixed(2);
				$('BasketItemWeight').show();
			} else {
				value = 0;
				$('BasketItemWeight').hide();
				unitText = ' $' + Number(selectedProduct.Orderable.price).toFixed(2) + ' per ' + selectedProduct.Orderable.ordered_by;
			}
		} else {
			$('BasketItemWeight').show();
		}
		$('BasketItemWeightLabel').update(labelText);
		$('BasketItemWeightUnit').update(unitText);
		$('BasketItemWeight').value = value;
	}
	
	$('ProducerId').observe('change', updateProductDropdown);
	$('ProductId').observe('change', updatePriceWeightLabel);
	updateProductDropdown();
	updatePriceWeightLabel();
	
</script>
<?php

}

?>
<h3>Frequently Asked Questions</h3>
<ul>
<li><strong>How do I submit my order?</strong>
<p>There's no need to submit the order.  Whatever is in your basket
when the order cycle closes is your order.  At that time, your order
is transferred to your invoice, and is sent to each producer to fill.</p></li>
<li><strong>Can I write a check for this now?</strong>
<p>Your total is an estimate.  Your exact total will not be calculated
until you pick up your order on the pickup day, because many products are
individualy weighed and priced by that weight.  Be prepared for your
total to be different on arrival.</p></li>
</ul>
